<template>
  <div>
    <el-button type="primary" @click="openEditDialog">新增</el-button>
    <el-button type="danger" :disabled="!multipleSelection.length" @click="deleteRows">删除</el-button>
    <el-card>
      <el-form :inline="true" :model="Page" class="demo-form-inline">
    <el-form-item label="商品名称">
      <el-select v-model="Page.sId" placeholder="请选择商品名称" filterable>
            <el-option v-for="item in goods" :key="item.sId" :label="item.goodsName" :value="item.sId"/>
          </el-select>
    </el-form-item>
    
    <el-form-item label="生产批次">
      <el-input v-model="Page.batch"  />
    </el-form-item>
    <el-form-item label="保质期（天）">
      <el-input v-model="Page.shelfLife"/>
    </el-form-item>
    <el-form-item label="生产许可证号">
      <el-input v-model="Page.licenseNumber" />
    </el-form-item>
    <el-form-item label="生产企业">
      <el-input v-model="Page.enterprise"  />
    </el-form-item>
    <el-form-item >
      <el-button type="danger"  @click="opne">重置</el-button>
    </el-form-item>
  </el-form>
    </el-card>
    <el-table
      :data="tableData"
      style="width: 100%; margin-top: 16px"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" />
      <el-table-column prop="goodsName" label="商品名称" />
      <el-table-column prop="batch" label="生产批次" />
      <el-table-column prop="shelfLife" label="保质期（天）" />
      <el-table-column prop="licenseNumber" label="生产许可证号" />
      <el-table-column prop="enterprise" label="生产企业" />
      <el-table-column label="信息完整度" width="120">
        <template #default="scope">
          <span :style="{ color: scope.row.percentage === 100 ? '#67C23A' : '#F56C6C' }">
            {{ scope.row.percentage }}%
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260">
        <template #default="scope">
          <el-link @click="viewDetail(scope.row)">详情</el-link>&nbsp;&nbsp;
          <el-link @click="editRow(scope.row)">修改</el-link>&nbsp;&nbsp;
          <el-link @click="">导出溯源码</el-link>&nbsp;&nbsp;
          <el-link type="danger" @click="deleteRows(scope.row.id)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="editDialogVisible" :title="title" width="500px">
      <el-form :model="editForm" :rules="editRules" label-width="120px">
        <el-form-item label="商品名称" prop="sId">
          <el-select v-model="editForm.sId" placeholder="请选择商品名称" filterable>
            <el-option v-for="item in goods" :key="item.sId" :label="item.goodsName" :value="item.sId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="生产批次" prop="batch">
          <el-input v-model="editForm.batch" maxlength="30" show-word-limit placeholder="请输入生产批次" />
        </el-form-item>
        <el-form-item label="保质期（天）" prop="shelfLife">
          <el-input-number v-model="editForm.shelfLife" :min="1" :max="999" controls-position="right" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="生产许可证号" prop="licenseNumber">
          <el-input v-model="editForm.licenseNumber" maxlength="30" show-word-limit placeholder="请输入生产许可证号" />
        </el-form-item>
        <el-form-item label="生产企业" prop="enterprise">
          <el-input v-model="editForm.enterprise" maxlength="30" show-word-limit placeholder="请输入生产企业" />
        </el-form-item>
        <el-form-item label="封面图" prop="url" class="anime-form-item">
          <el-upload class="avatar-uploader" action="http://localhost:5050/api/UpFail/Upload"
      :show-file-list="false" :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <img v-if="editForm.url" :src="editForm.url" style="width: 150px;height: 200px;"
          class="avatar" />
      <el-icon v-else class="avatar-uploader-icon">
          <Plus />
      </el-icon>
  </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import axios from 'axios';
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus';
import { ref,reactive,onMounted,watch } from 'vue'
import { useRouter } from 'vue-router'
//重置
const opne=()=>{
  Page.sId="",
  Page.batch="",
  Page.shelfLife="",
  Page.licenseNumber="",
  Page.enterprise=""
}
const router=useRouter();
const tableData = ref([])
//分页查询
const Page=reactive({
  totalPage:0,
  totalCount:0,
  PageIndex:1,
  PageSize:15,
  sId:'',
  batch:"",
  shelfLife:'',
  licenseNumber:"",
  enterprise:"",
})

//显示
const GetTraceablity=()=>{
  axios.get("http://localhost:5050/api/Maxage/GetAccount",{params:{
    PageIndex:Page.PageIndex,
    PageSize:Page.PageSize,
    sId:Page.sId,
    batch:Page.batch,
    shelfLife:Page.shelfLife,
    licenseNumber:Page.licenseNumber,
    enterprise:Page.enterprise
  }})
.then(res=>{

  tableData.value=res.data.data.data
  Page.totalCount=res.data.data.totalCount
  Page.totalPage=res.data.data.totalPage
  console.log(res.data.data.data.batch)

})
}
//商品下拉框
const goods = ref<{ sId: string; goodsName: string }[]>([])
const Getgoods=()=>{
  axios.get("http://localhost:5050/api/Maxage/GetGoods")
.then(res=>{
  goods.value=res.data.data
})
}
onMounted(()=>{
  GetTraceablity();
  Getgoods();
})
watch(Page,()=>{
  GetTraceablity();
})
const title=ref("");
const editDialogVisible = ref(false)

const multipleSelection = ref<any[]>([])
// 改进版 - 添加持久化支持
const generateDateBasedNumber = (incrementLength: number = 4) => {
  const now = new Date();
  const datePart = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
  
  // 从localStorage读取或初始化计数器
  const storageKey = `dateNumCounter_${datePart}`;
  let currentCount = localStorage.getItem(storageKey);
  
  // 如果localStorage中没有值，则初始化为0
  if (currentCount === null) {
    currentCount = '0';
  }
  
  // 转换为数字，递增，然后转回字符串
  const numericCount = parseInt(currentCount, 10) + 1;
  currentCount = numericCount.toString();
  
  // 保存新的计数器值
  localStorage.setItem(storageKey, currentCount);

  // 确保incrementLength是数字，然后生成递增部分
  const incrementPart = currentCount.padStart(incrementLength, '0');
  
  return datePart + incrementPart;
};
//表单
const editForm = reactive({
  id:0,
  sId: '',
  batch:generateDateBasedNumber(),
  shelfLife: 0,
  licenseNumber: '',
  enterprise: '',
  percentage:0,
  url:'',
  createUserName:localStorage.getItem("accountName")||"",
  UpdateUserName:localStorage.getItem("accountName")||""
})

//
const fileList = ref<{ name: string; url?: string; uid: string; response?: { url?: string } }[]>([]);
//正则表达式
const editRules = {
  sId: [{ required: true, message: '请选择商品名称', trigger: 'change' }],
  batch: [
    { required: true, message: '请输入生产批次', trigger: 'blur' },
    { min: 1, max: 30, message: '长度在1-30字符', trigger: 'blur' }
  ],
  shelfLife: [{ required: true, type: 'number', message: '请输入保质期', trigger: 'blur' }],
  licenseNumber: [
    { required: true, message: '请输入生产许可证号', trigger: 'blur' },
    { min: 1, max: 30, message: '长度在1-30字符', trigger: 'blur' }
  ],
  enterprise: [
    { required: true, message: '请输入生产企业', trigger: 'blur' },
    { min: 1, max: 30, message: '长度在1-30字符', trigger: 'blur' }
  ],
  url: [
    { required: false, message: '请上传检验报告', trigger: 'change' }
  ]
}
//生产批次


//新增弹出框
const openEditDialog=()=> {
  title.value="新增"
  editDialogVisible.value = true
  fileList.value = [];
  editForm.url = '';
}
//跳转
function viewDetail(row:any) {
  localStorage.setItem("batch",row.batch);
  router.push({
    path:("/Detail")
  })
}
const editRow = (row: any) => {
  title.value = "修改";
  editForm.id = row.id;
  editForm.sId = row.sId;
  editForm.batch = row.batch;
  editForm.enterprise = row.enterprise;
  editForm.shelfLife = row.shelfLife;
  editForm.percentage = row.percentage;
  editForm.licenseNumber = row.licenseNumber;
  editForm.createUserName=row.createUserName;
  editForm.url=row.url
  editDialogVisible.value = true;
}
function handleSelectionChange(val: any[]) {
  multipleSelection.value = val;
}
//图片
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,

) => {
    editForm.url = response
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
   
    return true
}
//新增修改
const submitEdit=()=> {
  if(editForm.id==0)
  {
    axios.post("http://localhost:5050/api/Maxage/AddTraceablity", editForm)
    .then(res=>{
      if(res.data.code==200)
    {
      ElMessage.success(res.data.message);
      editDialogVisible.value=false;
      GetTraceablity();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
    })
  }
  else
  {
    axios.put("http://localhost:5050/api/Maxage/UpdateTraceablity", editForm)
    .then(res=>{
      if(res.data.code==200)
    {
      ElMessage.success(res.data.message);
      editDialogVisible.value=false;
      GetTraceablity();
    }
    else
    {
      ElMessage.error(res.data.message);
    }
    })
  }
}
//删除
const deleteRows = (id?: number) => {
  let Ids: number[] = [];
  if (typeof id === 'number') {
    Ids = [id];
  } else {
    Ids = multipleSelection.value.map(row => row.id);
  }
  if (!Ids.length) {
    ElMessage.warning('请选择要删除的数据');
    return;
  }
  axios.post("http://localhost:5050/api/Maxage/BatchDeleteTraceablity", 
    { Ids },
    { headers: { 'Content-Type': 'application/json' } }
  )
    .then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.message);
        GetTraceablity();
      } else {
        ElMessage.error(res.data.message);
      }
    });
}
</script>

<script lang="ts">
export default { name: 'TraceabilityList' }
</script> 

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>